<?php


namespace app\common\cachemodel;

use app\common\lib\exception\ApiException;
use app\common\model\BaseCache;
use Exception;
use think\Log;
use XznsTools\cache\CacheManage;

class MentalQuestionModel extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.mt_questions';
    protected $cacheModel = 'mental_test.question';

    private $LOG_PRE = '心里测试Model：';

    private $LIST_KEYS = ['id', 'oid', 'name', 'short_describe', 'picture', 'price_original', 'price_discount', 'count_test', 'ocategory'];

    /**
     * 根据oid查询问题详情（因为qid有子类child_id）
     * @param $qid
     * @param string $child_id
     * @return array|bool|mixed|string
     * @throws Exception
     */
    public function getChildDetail($qid, $child_id = '')
    {
        return CacheManage::getInstance()->setCacheConfig($this->cacheModel, $qid . ':' . $child_id)
            ->getDataAndSet(function () use ($qid, $child_id)
            {
                try
                {
                    $data = $this->where(['parent_id' => $qid, 'oid' => $child_id])->field('id,name,short_describe,picture,price_original,price_discount,count_test,ocategory,type,question_num,report_size,intro_picture,detail_desc,scale_intro,child_scales,oid,pure_detail_desc')->findOrFail()->toArray();
                }
                catch (Exception $e)
                {
                    $data = [];
                }

                return $data;
            });
    }

    /**
     * 查询问题详情数据
     * @param int $qid 问题id
     * @param array $field
     * @param int $child_id 子类id
     * @return mixed
     * @throws ApiException
     */
    public function getQuestionDetailById($qid = 0, $field = [], $child_id = 0)
    {
        try
        {
            if ($child_id)
            {//获取子类详情
                $question = $this->getChildDetail($qid, $child_id);
            } else
            {
                $question = $this->getInfoById($qid, $field);
            }
            //类型转换
            if (isset($question['id']))
            {
                $question['id'] = (int)$question['id'];
            }
            if (isset($question['type']))
            {
                $question['type'] = (int)$question['type'];
            }
            if (isset($question['report_size']))
            {
                $question['report_size'] = (int)$question['report_size'];
            }
            if (isset($question['count_test']) && (int)$question['count_test'] > 10000)
            {
                $question['count_test'] = number_format($question['count_test'] / 10000.0, 1) . 'w';
            }
            return $question;
        }
        catch (Exception $e)
        {
            Log::write($this->LOG_PRE . '获取详情异常：' . $e->getMessage() . '(line:' . $e->getLine() . ')', 'error', true);
            throw new ApiException('问题获取异常！', 200, 0);
        }
    }

    /**
     * 获取热门问题
     * @param int $category 分类 [0, 1, 2, 3, 4, 5]=》['精选', '情感', '人际', '职场', '健康', '性格']
     * @param int $sort 排序 [0, 1, 2, 3, 4]=》['默认', '按热度倒序', '按价格倒序', '只看付费', '只看免费']
     * @param int $page
     * @return array|mixed
     * @throws Exception
     */
    public function getQuestionList($category = 0, $sort = 0, $page = 1)
    {
        if (!in_array($category, [0, 1, 2, 3, 4, 5]))
        {
            throw new ApiException('分类错误！', 200, 0);
        }
        if (!in_array($sort, [0, 1, 2, 3, 4]))
        {
            throw new ApiException('排序错误！', 200, 0);
        }

        $data = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel, $category)
            ->setPage($page)
            ->setListKeyType($sort)
            ->setSort('desc')
            ->getListPageDataIds(function ($ids = [], $isCache = true, $sortType = 'desc') use ($category, $sort)
            {

                $resData = $this->getInfoByIdsInData([], [$category, $sort], 'desc');
                $result = [];
//                排序 [0, 1, 2, 3, 4]=》['默认', '按热度倒序', '按价格倒序', '只看付费', '只看免费']
                foreach ($resData as $id => $v)
                {
                    switch ($sort)
                    {
                        case 0:
                        case 3:
                        case 4:
                        {
                            $result[$v['id']] = ['id' => $v['id'], 'score' => $v['sort']];
                            break;
                        }
                        case 1:
                        {
                            $result[$v['id']] = ['id' => $v['id'], 'score' => $v['count_test']];
                            break;
                        }
                        case 2:
                        {
                            $result[$v['id']] = ['id' => $v['id'], 'score' => $v['price_discount']];
                            break;
                        }
                    }

                }
                return $result;
            }, 'score', 1);

        $ids = array_keys($data['data']);
        //获取详情数据
        $resData = $this->batchGetInfoByIds($ids, $this->LIST_KEYS);
        $list = [];
        foreach ($resData as $k => $v)
        {
            //处理已测数量显示
            if (isset($v['count_test']) && $v['count_test'] > 10000)
            {
                $v['count_test'] = number_format($v['count_test'] / 10000.0, 1) . 'w';
                $v['scale_pool_id'] = $v['oid'];
//                    unset($v['oid']);
            }
            $list[] = $v;
        }

        $data['data'] = $list;
        return $data;

    }

    /**
     * 批量获取数据
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|false|string|void
     */
    public function getInfoByIdsInData($ids, $type = [], $sortType)
    {

        $field_sort = '';

        if ($ids)
        {//查询详情
            $fields = 'id,name,short_describe,picture,price_original,price_discount,count_test,ocategory,type,question_num,report_size,intro_picture,detail_desc,scale_intro,child_scales,oid,pure_detail_desc';
            $where = ['id' => ['in', $ids]];
        } else
        {//查询列表ids
            $fields = 'id,sort,count_test,price_discount';
            $category = $type[0];
            if (isset($type))
            {
                $sort = $type[1];
            } else
            {
                $sort = 0;
            }

            $where['online_type'] = 2;//是否上线：【1=》未上线；2=》已上线】
            $where['parent_id'] = 0;
            if ($category)
            {
                $categories = ['精选', '情感', '人际', '职场', '健康', '性格'];
                $where['ocategory'] = $categories[$category];
            }
            // ['默认', '按热度倒序', '按价格倒序', '只看付费', '只看免费']
            switch ($sort)
            {
                case 0:
                {
                    $field_sort = 'sort';
                    break;
                }
                case 1:
                {
                    $field_sort = 'count_test';
                    break;
                }
                case 2:
                {
                    $field_sort = 'price_discount';
                    break;
                }
                case 3:
                {//类型【1：免费；2：付费；】
                    $where['type'] = 2;
                    break;
                }
                case 4:
                {//类型【1：免费；2：付费；】
                    $where['type'] = 1;
                    break;
                }

            }
        }
        try
        {
            $data = $this->where($where)->order($field_sort, 'desc')->column($fields, 'id');
        }
        catch (Exception $e)
        {
            $data = [];
            Log::write($this->LOG_PRE . '获取详情异常：' . $e->getMessage(), 'error', true);
        }
        if ($ids)
        {
            $list = [];
            foreach ($ids as $v)
            {
                $list[$v] = $data[$v];
            }
            return $list;
        }
        return $data;
    }


    /**
     * 随机获取推荐问题
     * @param string $category 题目级别 ['性格', '情感', '职场', '健康', '人际', '亲子', '能力']
     * @param int $num 获取题目数量
     * @return array
     * @throws Exception
     */
    public function getRecommondQuestions($category = '情感', $num = 0): array
    {
        //todo 校验$category
        $data = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel, 'list_recommends')
            ->setPage(-1)
            ->setListKeyType($category)
            ->getListPageDataIds(function () use ($category)
            {
                try
                {// $where = ['online_type' => 2];//是否上线：【1=》未上线；2=》已上线】
                    $resData = $this->where('ocategory', $category)->where('online_type', 2)->column('id');
                    $data = [];
                    foreach ($resData as $idItem)
                    {
                        $data[$idItem] = ['id' => $idItem];
                    }
                }
                catch (Exception $e)
                {
                    Log::write($this->LOG_PRE . '获取随机问题获取异常：' . $e->getMessage(), 'error', true);
                    $data = [];
                }

                return $data;
            });

        if (isset($data['data']))
        {
            //todo 剔除当前的问题
            $count = count($data['data']);
            $num = $num > $count ? $count : $num;
            $ids = array_rand($data['data'], $num);
            if (!is_array($ids))
            {
                $ids = [$ids];
            }
            //获取详情数据
            $list = $this->batchGetInfoByIds($ids, $this->LIST_KEYS);
            $recommend_list = [];//返回的数据
            //组装数据
            foreach ($list as $k => $v)
            {
                $recommend_list[] = $v;
            }
        } else
        {
            $recommend_list = [];
        }
        return $recommend_list;
    }

}
